package com.ruoyi.web.controller.tool;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
@Component
public class OssTools {
    private  String secretId = "AKIDtiOE5rW2RzX0Mbk0AOXWPEuTxHi4HMK8";
    private  String secretKey ="t3DZM7wc8Uglku19Qky7EFSf4a0LZhgW";
    private  String bucketName="dgrxcx-1321578486";
    private  String region ="ap-chengdu";
    private  String baseUrl ="https://dgrxcx-1321578486.cos.ap-chengdu.myqcloud.com";

    //腾讯云cos对象存储
    //上传本地文件
    public String uploadFile(File file) throws Exception{
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            String fileName = file.getName();
            resizeImageIfNeeded(file, 1000);
            //上传oss
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName,file);
            COSClient cosClient = createCli();
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            return baseUrl+"/"+fileName;
        }
        catch (Exception e)
        {
            return null;
        }
    }

    //新增的重载方法
    public String uploadFile(File file, String ossFileName) throws Exception {
        try {
            resizeImageIfNeeded(file, 1000);
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, ossFileName, file);
            COSClient cosClient = createCli();
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            return baseUrl + "/" + ossFileName;
        } catch (Exception e) {
            return null;
        }
    }

    public void resizeImageIfNeeded(File imageFile, int maxWidth) throws Exception {
        String fileName = imageFile.getName();
        String ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
        String format = ("png".equals(ext) || "jpg".equals(ext) || "jpeg".equals(ext)) ? ext : "jpg";

        BufferedImage image = ImageIO.read(imageFile);
        if (image != null && image.getWidth() > maxWidth) {
            int newWidth = maxWidth;
            int newHeight = (int) ((double) image.getHeight() * newWidth / image.getWidth());
            int imageType = "png".equals(format) ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB;
            Image tmp = image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
            BufferedImage resized = new BufferedImage(newWidth, newHeight, imageType);
            Graphics2D g2d = resized.createGraphics();
            g2d.drawImage(tmp, 0, 0, null);
            g2d.dispose();
            ImageIO.write(resized, format, imageFile);
        }
    }

    // 删除单个文件(不带版本号, 即bucket未开启多版本)
    @PostMapping("/delFile")
    private  void delSingleFile(String fileName) {
        try {
            COSClient cosClient = createCli();
            String key = fileName;
            cosClient.deleteObject(bucketName, key);
        } catch (CosServiceException e) { // 如果是其他错误, 比如参数错误， 身份验证不过等会抛出CosServiceException
            e.printStackTrace();
        } catch (CosClientException e) { // 如果是客户端错误，比如连接不上COS
            e.printStackTrace();
        }

    }
    private  COSClient createCli() {
        // 1 初始化用户身份信息(secretId, secretKey)

        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        return cosclient;
    }
}
